﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Protocol.Transport
{
    public class LiteMessageChannel : DataChannel
    {
        protected override byte[] EncaseMessage(IList<byte> data)
        {
            var length = (ushort) (data.Count/4);
            var package = new List<byte>();
            if (PackageNumber == 0) package.Add(0xEF);
            if (length < 254) package.Add((byte) (length));
            else
            {
                package.Add(0x7F);
                package.AddRange(BitConverter.GetBytes(length).Skip(1));
            }

            package.AddRange(data);
            return package.ToArray();
        }

        protected override byte[] UncaseMessage(IList<byte> bytes)
        {
            var length = bytes[0] == 0x7f
                ? bytes[1] + (bytes[2] << 8) + (bytes[3] << 16) + 1
                : bytes[0];
           // if (length != bytes.Count/4)
             //   throw new Exception("Invalid length");

            var skip = bytes[0] == 0x7F ? 4 : 1;
            return bytes.Skip(skip).Take(length * 4).ToArray();
        }
    }
}
